import { app, protocol, BrowserWindow, globalShortcut, Menu, ipcMain, dialog, Notification, Tray, session } from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
import path from 'path';
import { browserWindowOption, winURL, disabledKeys, userTasks } from './config';
const remote = require('@electron/remote/main')
remote.initialize();
const logo = path.join(__static, 'logo.png')
const transparent = path.join(__static, 't.png')
const ex = process.execPath;
global.Timer = null

const startWindow = () => {
  const isDevelopment = process.env.NODE_ENV !== 'production';
  let win = null;
  app.commandLine.appendSwitch('wm-window-animations-disabled');

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });
  protocol.registerSchemesAsPrivileged([
    {
      scheme: 'app',
      privileges: {
        secure: true,
        standard: true
      }
    }
  ]);


  function registerLocalMediaProtocol () {
    protocol.registerFileProtocol('local-media', (request, callback) => {
      const url = request.url.replace(/^local-media:\/\//, '')
      // Decode URL to prevent errors when loading filenames with UTF-8 chars or chars like "#"
      const decodedUrl = decodeURI(url) // Needed in case URL contains spaces
      try {
        return callback(path.join(__static, decodedUrl))
      } catch (error) {
        console.error(
          'ERROR: registerLocalMediaProtocol: Could not get file path:',
          error
        )
      }
    })
  }

  const createWindow = () => {
    // 如果有webpack启动的server
    if (process.env.WEBPACK_DEV_SERVER_URL) {

      win = new BrowserWindow(browserWindowOption());
      // 默认打开webpack启动的serve
      win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
      if (!process.env.IS_TEST) win.webContents.openDevTools();
    } else {
      // 注册一个协议
      createProtocol('app');
      win = new BrowserWindow(browserWindowOption());
      win.loadURL(winURL);
      if (process.env.VUE_APP_OPENTOOL) {
        win.webContents.openDevTools();
      }
    }
    remote.enable(win.webContents)
    win.once('ready-to-show', () => {
      win.show();
    });

    win.on('closed', () => {
      win = null;
    });
  };

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });


  async function handleFileOpen (data) {
    const res = await dialog.showOpenDialogSync({
      properties: ['openFile'],
      title: "请选择图片",
      icon: logo,
      filters: [
        { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
      ],
    })
    return res
  }


  function initTrayIcon () {
    const tray = new Tray(logo)
    const trayContextMenu = Menu.buildFromTemplate([
      {
        label: '打开', type: 'normal', click: () => {
          win.show()
        }
      },
      {
        label: '退出', type: 'normal', click: () => {
          app.exit()
        }
      },
    ]);

    tray.setContextMenu(trayContextMenu)

    tray.setToolTip('MeChat')
    tray.setTitle('MeChat')


    tray.on('click', () => {
      win.setSkipTaskbar(false)
      if (win.isVisible()) {
        if (!win.isFocused()) return win.focus()
        win.hide()
      } else {
        win.show()
      }
    });
    tray.on('right-click', () => {
      // tray.popUpContextMenu(trayContextMenu);
    });
    return tray
  }

  app.on('ready', async () => {
    const tray = initTrayIcon()
    registerLocalMediaProtocol()
    ipcMain.handle('openFile', (event, data) => {
      return handleFileOpen()
    })
    ipcMain.handle('notification', (event, data) => {
      new Notification(data).show()
    })
    ipcMain.handle('setWinSize', (event, data) => {
      win.setSize(data.width, data.height, false)
      if (data.center) {
        win.center()
      }
    })

    ipcMain.handle('setMinimumSize', (event, options) => {
      win.setMinimumSize(options.width, options.height)
    })


    ipcMain.handle('setMinimize', () => {
      win.setSkipTaskbar(false)
      win.minimize()
    })

    ipcMain.handle('setMaximize', (event, screen) => {

      if (typeof screen === 'boolean') {
        screen ? win.maximize() : win.unmaximize()
      }
      return win.isMaximized()
    })

    ipcMain.handle('hide', () => {
      win.hide()
      win.setSkipTaskbar(true)
    })

    ipcMain.handle('setResizable', (e, data) => {
      win.setResizable(data)
    })

    ipcMain.handle("showMessage", (event, options) => {
      return dialog.showMessageBoxSync(win, options)
    })

    ipcMain.handle('sendMsg', (event, obj) => {
      const data = { ...obj }
      BrowserWindow.fromId(data.id).webContents.send('getMsg', data)
    })

    ipcMain.handle('windowAction', (event, data) => {
      const obj = JSON.parse(data)
      const win = BrowserWindow.fromId(obj.id)
      return win[obj.action](obj.params)
    })


    ipcMain.handle('twinkle', (event, data) => {
      clearInterval(global.Timer)
      console.log(win.isVisible())
      if (win.isVisible()) return
      let count = 0
      if (data.open) {
        global.Timer = setInterval(() => {
          count += 1
          if (count % 2 == 0) {
            tray.setImage(transparent)
          } else {
            tray.setImage(logo)
          }
        }, 500);
      } else {
        tray.setImage(logo)
      }
    })


    // 开启 开机自启动
    ipcMain.on('openAutoStart', () => {
      app.setLoginItemSettings({
        openAtLogin: true,
        path: ex,
        args: []
      });
    });
    // 关闭 开机自启动
    ipcMain.on('closeAutoStart', () => {
      app.setLoginItemSettings({
        openAtLogin: false,
        path: ex,
        args: []
      });
    })

    ipcMain.handle('getLoginItemSettings', () => {
      return app.getLoginItemSettings()
    })

    ipcMain.on('switchPage', () => {
      if (win.isVisible()) {
        win.hide()
      } else {
        win.show()
      }
    })

    // 快捷键禁用
    for (const key of disabledKeys()) {
      globalShortcut.register(key, () => void 0);
    }
    // updater();
    createWindow();

    win.on('show', () => {
      clearInterval(global.Timer)
      tray.setImage(logo)
    })
  });

  app.setUserTasks(userTasks);

  if (isDevelopment) {
    if (process.platform === 'win32') {
      process.on('message', data => {
        if (data === 'graceful-exit') {
          app.quit();
        }
      });
    } else {
      process.on('SIGTERM', () => {
        app.quit();
      });
    }
  }
};

export default startWindow;